package com.renatn.yach.dao.jpa;

import com.renatn.yach.dao.GenericDao;
import com.renatn.yach.domain.DomainObject;
import com.renatn.yach.domain.YachList;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;

/**
 * User: rnasyrov
 * Date: 10.01.12
 * Time: 15:01
 */
public class GenericDaoJpa<T extends DomainObject> implements GenericDao<T> {
    
    private Class<T> type;
    
    protected EntityManager entityManager;

    public GenericDaoJpa(Class<T> type) {
        super();
        this.type = type;
    }
    
    @PersistenceContext 
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public T get(Long id) {
        return (T) entityManager.find(type, id);
    }

    @Override
    public List<T> getAll() {
        CriteriaQuery<T> query = entityManager.getCriteriaBuilder().createQuery(type);
        query.from(type);
        return entityManager.createQuery(query).getResultList();
    }

    @Override
    public void save(T object) {
        entityManager.persist(object);
    }
}
